package info.emm.weiyipro.demo.sdk.system;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.media.AudioDeviceInfo;
import android.media.AudioManager;
import android.os.Build;
import android.util.Log;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * Created by Z on 2019/1/17.
 */

public class AudioPlayManager {
    /**
     * 外放模式
     */
    public static final int MODE_SPEAKER = 0;

    /**
     * 有线耳机模式
     */
    public static final int MODE_HEADSET = 1;

    /**
     * 听筒模式
     */
    public static final int MODE_EARPIECE = 2;

    /**
     * 蓝牙耳机模式
     */
    private static final int MODE_BLUETH_HEADSET = 3;

    private static AudioPlayManager audioPlayManager;

    private AudioManager audioManager;

    private Context context;

    private int currentMode = MODE_SPEAKER;
    private String TAG = AudioPlayManager.class.getSimpleName();
    private HeadsetReceiver headsetPlugReceiver;
    private static volatile ExecutorService audioQueue = Executors.newSingleThreadExecutor();
    ;
    private boolean isLound = false;

    public static AudioPlayManager getManager() {
        if (audioPlayManager == null) {
            synchronized (AudioPlayManager.class) {
                audioPlayManager = new AudioPlayManager();
            }
        }
        return audioPlayManager;
    }

    public void init(Context context) {
        this.context = context;
        initAudioManager();
    }

    /**
     * 初始化音频管理器
     */
    private void initAudioManager() {
        audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        headsetPlugReceiver = new HeadsetReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(AudioManager.ACTION_HEADSET_PLUG);//有线耳机D
        filter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);//通话状态
        filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
        filter.addAction("android.bluetooth.headset.profile.action.ACTIVE_DEVICE_CHANGED");
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        context.registerReceiver(headsetPlugReceiver, filter);
    }

    /**
     * 获取当前播放模式
     *
     * @return
     */
    public int getCurrentMode() {
        return currentMode;
    }

    /**
     * 切换到听筒模式
     */
    public void changeToEarpieceMode() {
        isLound = false;
        refreshAudioRoute(isLound);
    }

    /**
     * 切换到有线耳机模式
     */
    public void changeToHeadsetMode() {
        currentMode = MODE_HEADSET;
        if (audioManager.getMode() != AudioManager.MODE_IN_COMMUNICATION) {
            audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
        }
        audioManager.setSpeakerphoneOn(false);
    }

    /**
     * 切换到蓝牙耳机模式
     */
    public void changeToBluethHeadsetMode() {
        currentMode = MODE_BLUETH_HEADSET;
        if (audioManager.getMode() != AudioManager.MODE_IN_CALL) {
            audioManager.setMode(AudioManager.MODE_IN_CALL);
        }
        audioManager.startBluetoothSco();
    }


    /**
     * 切换到外放模式
     */
    public void changeToSpeakerMode() {
        isLound = true;
        refreshAudioRoute(isLound);
    }



    public void changeNormal() {
        if (audioManager != null) {
            audioManager.setMode(AudioManager.MODE_NORMAL);
        }
    }


    public void refreshAudioRoute() {

        refreshAudioRoute(isLound);

    }

    public void refreshAudioRoute(boolean load) {
        audioQueue.execute(() -> {
            if (audioManager != null) {
                try {
                    BluetoothAdapter blueadapter = BluetoothAdapter.getDefaultAdapter();
                    if (blueadapter != null && blueadapter.isEnabled()
                            && blueadapter.getProfileConnectionState(BluetoothProfile.HEADSET) == BluetoothProfile.STATE_CONNECTED) {


                        if (audioManager.getMode() != AudioManager.MODE_IN_CALL) {
                            audioManager.setMode(AudioManager.MODE_IN_CALL);
                        }
                        audioManager.setBluetoothScoOn(true);
                        audioManager.startBluetoothSco();

                        Log.d(TAG, "isBluetoothScoOn: " + audioManager.isBluetoothScoOn());
                    } else {
                        Log.e(TAG, "Bluetooth mode=" + audioManager.getMode());
                        audioManager.setSpeakerphoneOn(!audioManager.isWiredHeadsetOn() && load);
                        if (((Build.BRAND.equalsIgnoreCase("google")
                                || Build.MANUFACTURER.equalsIgnoreCase("huawei")
                                || Build.MANUFACTURER.equalsIgnoreCase("samsung")) && !load)
                                || Build.MANUFACTURER.equalsIgnoreCase("xiaomi")) {
                            if (audioManager.getMode() != AudioManager.MODE_IN_CALL) {
                                audioManager.setMode(AudioManager.MODE_IN_CALL);
                            }
                        } else {
                            if (audioManager.getMode() != AudioManager.MODE_IN_COMMUNICATION) {
                                audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e(TAG, "refreshAudioRouteException: " + e.getMessage());
                }

            }
        });

    }
}
